/******************
机构变更
* */
<template>
  <el-dialog
    width="80%"
    :title="dialogTitle"
    :close-on-click-modal="false"
    :visible.sync="visible"
    top="8vh"
    @close="closeDialog()"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      label-position="right"
      label-width="120px"
      @keyup.enter.native="dataFormSubmit()"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="部门">
            <span>{{dataForm.assessDeptName}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="考核周期">
            <span>{{dataForm.period}}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="height: 10px; border-top: 1px solid #b0bde2"></div>
    <div class="tabBox">
      <div class="btnBox">
        <div>
          <el-tooltip effect="dark" content="选择指标" placement="top">
            <el-button icon="el-icon-plus" type="success" circle @click="showTarLibrary"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除指标" placement="top">
            <el-button :disabled="canDelete" type="danger" icon="el-icon-delete" circle   @click="deleteIndex"></el-button>
          </el-tooltip>
        </div>
       <!-- <div>
          <el-button @click="repeatTarget" type="primary">复用指标</el-button>
        </div>-->
      </div>
    </div>
    <el-row>
      <el-form  ref="targetForm" :model="targetDataForm">
      <el-table
        style="width: 100%;margin-top:20px"
        :data="dataList"
        border
        stripe
        header-align="center"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="type" align="center" label="指标类别" width="140"></el-table-column>
        <el-table-column prop="name" align="center" label="指标名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="weight" align="center" label="权重(%)" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>
              <el-input v-model.number="scope.row.weight" @blur="getNum(scope.row, scope.$index,'weight')"></el-input>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="formula" align="center" label="计算公式" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.formula}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="目标值" min-width="120">
          <template slot-scope="scope">
            <el-form-item :prop="'itemSetForm.' + scope.$index + '.targetValue'"
                          :rules="[{ required:true, message:'请填入目标值',trigger:'change'},
                               { min:0, max:200, message:'不可超过200个字符',trigger:'change'}]">
              <el-input :rows="1"
                        type="textarea"
                        v-model="targetDataForm.itemSetForm[scope.$index].targetValue" :clearable="true"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="unit" align="center" label="单位" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="completeValue" align="center" label="完成值获取方式" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select
              @change="$set(scope.row, scope.row.completeValue, $event)"
              :clearable="true"
              v-model="scope.row.completeValue"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dataFromList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="provideRealName"
          align="center"
          label="数据提供部门/人"
          show-overflow-tooltip
          width="200"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.isLiaison==0"
              style="color:blue"
              @click="showDataProvide(scope.row,scope.$index)"
            >
              {{scope.row.provideRealName}}
              <i class="el-icon-edit-outline"></i>
            </span>
            <span v-else style="color:blue" @click="showDataProvide(scope.row,scope.$index)">
              {{scope.row.provideDeptName}}
              <i class="el-icon-edit-outline"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="normRule" align="center" label="指标规则" show-overflow-tooltip></el-table-column>
        <!--<el-table-column prop="itemIndex" align="center" label="排序号" show-overflow-tooltip></el-table-column>-->
      </el-table>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      
      <el-button type="primary" plain @click="handleConfirm"  :disabled="saveBtnVisible">确定</el-button>
      <el-button type="primary" plain @click="closeDialog()">返回</el-button>
    </span>
    <!--选数据提供部门组件-->
    <FormulateDialog v-if="formulateDialog" ref="formulateDialog" @submitfy="submitfy1"></FormulateDialog>
    <!-- 考核指标库 -->
    <el-dialog title="业绩合同指标库" :visible.sync="dialogVisible" width="80%" append-to-body>
      <zhibiaoTable ref="zhibiaoRef" @func="getRow"></zhibiaoTable>
      <span slot="footer" class="dialog-footer">
        
        <el-button plain type="primary" @click="addZhibiao">添 加</el-button>
        <el-button plain @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 复用指标 -->
    <el-dialog title="请选择指标" :visible.sync="repeatVisible" width="80%" append-to-body>
      <el-table
        style="width: 100%;margin-top:20px"
        :data="repeatDataList"
        border
        stripe
        header-align="center"
        @selection-change="handleRepeatChange"
      >
        <el-table-column type="selection" header-align="center" width="55"></el-table-column>
        <el-table-column prop="bh" align="center" label="指标类别" width="140"></el-table-column>
        <el-table-column prop="sjbt" align="center" label="指标名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="realname" align="center" label="权重(%)" show-overflow-tooltip></el-table-column>
        <el-table-column prop="realname" align="center" label="计算公司" show-overflow-tooltip></el-table-column>
        <el-table-column prop="realname" align="center" label="目标值" show-overflow-tooltip></el-table-column>
        <el-table-column prop="realname" align="center" label="单位" show-overflow-tooltip></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button plain type="primary" @click="repeatVisible=false">添 加</el-button>
        <el-button plain @click="repeatVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import zhibiaoTable from "@/views/dailyExamine/components/targetIndexTable"; //指标表格
import { editExamin,getNormByTypeAndUserId,checkitem } from "@/api/dailyExamine/targetExamine/perORtarChange";
import FormulateDialog from "./formulateDialog"; //数据提供部门选择组件
import { validatenull } from "@/util/validate"; //判断空
import { remote as remoteDict } from "@/api/admin/dict"; //数据获取方式接口

export default {
  data() {
    return {
      canDelete: true, //是否能删除指标
      usercomment: false, //人员选择组件显隐
      fatherData: {}, //总部启动的考核数据
      repeatDataList: [], //复用指标数据
      chooseTarget: [], //选中的指标数组
      repeatList: [], //选中的复用指标
      repeatVisible: false, //复用指标弹窗显隐
      dialogVisible: false, //考核指标库显隐
      multipleSelection: [], //选中的指标
      dataList: [], //指标数组
      oldDataList:[],//原始表格数据
      deptcomment: false, //选择部门组件
      formulateDialog: false, //数据提供部门/人组件显隐
      options: [], //被考核部门数组
      dialogTitle: "修改指标", //弹窗标题
      visible: false, //最外层弹窗显隐
      saveBtnVisible:false,
      dataForm: {
        //表单对象
        ids: []
      },
      targetDataForm:{ //目标值数组
          itemSetForm: []
      },
      chooseDeptData: {}, //选择的数据提供部门人数据
      participantList: [], //被考核部门暂存数据
      submitForm: {
        //提交给后台的数据对象
        name: null, //考核名称
        participantList: [], //被考核部门
        kpiDetailList: [], //指标
        type: 1 //类型 0是人员 1 是机构
      },
      dataFromList:[],//数据获取方式列表
      loading:false

    };
  },
  components: {
    zhibiaoTable, //指标组件
    FormulateDialog
  },
  watch: {
      // 监听指标选中变化
      multipleSelection: {
          handler(val) {
              if (val.length !== 0) {
                  this.canDelete = false;
              } else {
                  this.canDelete = true;
              }
          },
          deep: true
      }
  },
  methods: {
      //权重\目标值必须为数字 保留两位小数
      getNum(row,index,type) {
          let value = '' ;
          if (type=='weight'){
              value = row.weight ;
          }else{
              value = row.targetValue ;
          }
          if (!validatenull(value)){
              if(isNaN(value)){
                  if (type=='weight'){
                      row.weight = '' ;
                  }else{
                      row.targetValue = '' ;
                  }
                  this.$message.warning('请输入数字')
              }else{
                  if (value && value.indexOf('.') > -1) {
                      if (type=='weight'){
                          row.weight = value.slice(0, value.indexOf('.') + 2)
                      }else{
                          row.targetValue = value.slice(0, value.indexOf('.') + 2)
                      }

                  } else {
                      if (type=='weight'){
                          row.weight = value
                      }else{
                          row.targetValue = value
                      }

                  }
              }
          }
      },
    // 删除指标
    deleteIndex() {
        let tempArr = [];
        this.dataList = this.dataList.filter(itt => {
            let tem = this.multipleSelection.filter(it => {
                return itt.renderIndex == it.renderIndex;
            });
            return tem.length == 0;
        });
        this.targetDataForm.itemSetForm= this.targetDataForm.itemSetForm.filter(itt => { //目标值对象数组也要同时删除
            let tem1 = this.multipleSelection.filter(it => {
                return parseInt(itt.normId) == parseInt(it.normId);
            });
            return tem1.length == 0;
        });
    },
    //筛选出姓名与职务
    shaiXuan(data, type) {
      var list = [],
        obj = {};
      if (type == "被考核机构") {
        for (var i in data) {
          list.push(data[i].jigouName);
        }
      }
      return list.toString();
    },
    // 数据提供人员选择的提交
    submitfyUser(data) {
      if (data.type == "shr") {
        this.dataList.map(it => {
          if (it.normId == this.chooseDeptData.normId) {
            this.$set(it, "provideRealName", data.tableDataUser[0].userName);
            this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
            this.$set(it, "provideUserId", data.tableDataUser[0].userId);
            this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
            this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
          }
        });
        this.personSelectChange();
      } else {
        this.options = data.tableDataUser;
        this.dataForm.ids = data.tableDataUser.map(it => {
          return it.userId;
        });
      }
    },
    // 展示数据提供部门
    showDataProvide(data, index) {
        this.chooseDeptData = data;
        this.formulateDialog = true;
        this.jsonData = JSON.stringify([{}]);
        this.providerIndex = index;
        this.$nextTick(() => {
            this.$refs.formulateDialog.init("12", "ndts", this.jsonData, "ndcj");
        });
    },
    // 选中复用数据
    handleRepeatChange(val) {
      this.repeatList = val;
    },
    // 复用指标
    // repeatTarget() {
    //   this.repeatVisible = true;
    // },
    // 添加指标
    addZhibiao() {
        let tempList = this.chooseTarget.map(it => {
            it.type = it.normLx;
            it.name = it.normName;
            it.formula = it.normGsname;
            it.formulaId = it.normGs;
            it.completeValue = '手动获取'; //it.normGetDate;
            it.keiExplain = it.normSm;
            it.unit = it.normDw;
            it.itemIndex = it.normPx;
            it.normId = it.normId ;
            this.targetDataForm.itemSetForm.push({'targetValue':it.targetValue,'normId':parseInt(it.normId)})
            return it;
        });

        //筛选出重复指标，并做提示
        let normNameList = [] ;
        for(let i = 0; i < tempList.length; i++) {
            let tempArr1 = tempList[i]
            for(let j = 0; j < this.dataList.length; j++) {
                let tempArr2 = this.dataList[j]
                if(parseInt(tempArr2.normId) ===parseInt( tempArr1.normId)){
                    normNameList.push(tempArr1.normName);
                    break;
                }
            }
        }
        if (normNameList.length>0){
            this.$message.error("“"+normNameList.toString()+"”不可重复添加") ;
        }

        // this.dataList = [...this.dataList, ...Object.assign(tempList)];
        const arr = [...this.dataList, ...Object.assign(tempList)]; //父子数据合并
        const newArr = arr.reduce(function (tempArr, item) { //去重
            if (tempArr.findIndex((ele) => parseInt(ele.normId) === parseInt(item.normId)) === -1) {
                tempArr.push(item)
            }
            return tempArr
        }, []);
        this.dataList = newArr ; //去重后的数据

        const arr1 = [...this.targetDataForm.itemSetForm, ...Object.assign(tempList)]; //父子数据合并(添加指标后，this.targetDataForm.itemSetForm有重复值)
        const newArr1 = arr.reduce(function (tempArr, item) { //去重
            if (tempArr.findIndex((ele) => parseInt(ele.normId) === parseInt(item.normId)) === -1) {
                tempArr.push(item)
            }
            return tempArr
        }, []);
        this.targetDataForm.itemSetForm = newArr1 ; //去重后的数据 this.targetDataForm.itemSetForm


        this.dialogVisible = false;
        this.dataList.map((it, index) => {
            it.renderIndex = index + 1;
        });


    },
    // 指标组件穿过来的数据
    getRow(rows) {
      this.chooseTarget = rows;
    },
    // 显示指标库
    showTarLibrary() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.zhibiaoRef.init(1, 1);
      });
    },
    // 选中指标
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 被考核部门选择
    personSelectChange(data) {
      this.participantList = [];
      this.options.map(it => {
        this.dataForm.ids.map(item => {
          if (item == it.deptId) {
            this.participantList.push({
              assessDeptId: it.deptId,
              assessDeptName: it.deptName,
              assessRealName: it.userName,
              assessUserId: it.userId,
              assessUserName: it.userCode
            });
          }
        });
      });
    },
    //   机构展示
    showDept() {
      this.deptcomment = true;
      this.$nextTick(() => {
        this.$refs.deptcomment.init("12", "jg", JSON.stringify({}), "htcj");
      });
    },
    // 部门组件选择后确定
    submitfy(data) {
      if (data.type == "shr") {
        this.dataList.map(it => {
          if (it.normId == this.chooseDeptData.normId) {
            it.provideRealName = data.tableDataUser[0].userName;
            it.provideUserName = data.tableDataUser[0].userCode;
            it.provideUserId = data.tableDataUser[0].userId;
            it.provideDeptName = data.tableDataUser[0].deptName;
            it.provideDeptId = data.tableDataUser[0].deptId;
          }
        });
      } else {
        this.options = data.tableDataUser;
        this.dataForm.ids = data.tableDataUser.map(it => {
          return it.deptId;
        });
      }
    },
    // 数据提供部门/人选择的确定
    submitfy1(data) {
        console.log(data);
        if (this.dialogTitle == "修改指标") {
            if (data.selectorgdata.length == 0) {
                this.isDept = false;
                this.dataList.map(it => {
                    if (it.renderIndex == this.chooseDeptData.renderIndex) {
                        this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
                        this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
                        this.$set(it, "provideUserId", data.tableDataUser[0].userId);
                        this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
                        this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
                        // this.$set(it, "isDept", false);
                        this.$set(it, "isLiaison", 0);
                    }
                });
            } else {
                this.isDept = true;
                this.dataList.map(it => {
                    if (it.renderIndex == this.chooseDeptData.renderIndex) {
                        this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
                        this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
                        this.$set(it, "provideUserId", data.selectorgdata[0].userId);
                        this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
                        this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
                        // this.$set(it, "isDept", true);
                        this.$set(it, "isLiaison", 1);
                    }
                });
            }
        } else {
            if (data.selectorgdata.length == 0) {
                this.isDept = false;
                this.dataList.map(it => {
                    if (it.normId == this.chooseDeptData.normId) {
                        this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
                        this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
                        this.$set(it, "provideUserId", data.tableDataUser[0].userId);
                        this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
                        this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
                        // this.$set(it, "isDept", false);
                        this.$set(it, "isLiaison", 0);
                    }
                });
            } else {
                this.isDept = true;
                this.dataList.map(it => {
                    if (it.normId == this.chooseDeptData.normId) {
                        this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
                        this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
                        this.$set(it, "provideUserId", data.selectorgdata[0].userId);
                        this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
                        this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
                        // this.$set(it, "isDept", true);
                        this.$set(it, "isLiaison", 1);
                    }
                });
            }
        }
    },
    // 确定
    handleConfirm() {
        this.$refs.targetForm.validate(valid => {
            if (valid) {
                this.saveBtnVisible = true ;
                this.submitForm.kpiDetailList = this.dataList.map(it => {
                    delete it.createDeptId;
                    delete it.createDeptName;
                    delete it.createTime;
                    delete it.createUserId;
                    delete it.createUserName;
                    delete it.dataState;
                    delete it.editDeptId;
                    delete it.editDeptName;
                    delete it.editTime;
                    delete it.editUserId;
                    delete it.editUserName;
                    delete it.tenantId;
                    it.finalScore = it.score;
                    //目标值塞回到指标项里
                    this.targetDataForm.itemSetForm.map(itt=>{
                        if (parseInt(it.normId)==parseInt(itt.normId)){
                            it.targetValue = itt.targetValue ;
                        }
                    })
                    return it;
                });

                //验证指标列表中数据提供部门/人不可为空
                let flag = this.submitForm.kpiDetailList.every( it=> {
                    return !validatenull(it.weight)&&!validatenull(it.targetValue)&&!validatenull(it.isLiaison) && ( (it.isLiaison==0 && !validatenull(it.provideRealName))||(it.isLiaison==1 && !validatenull(it.provideDeptName)))
                }) ;
                if(!flag){
                    this.saveBtnVisible = false ;
                    this.$message.error('权重、目标值、数据提供部门/人不可空');
                    return ;
                }

                //this.submitForm.name = this.dataForm.name;
                this.submitForm.assessId = this.fatherData.id;
                this.submitForm.period = this.fatherData.period;
                this.submitForm.assessBeginTime = this.fatherData.assessBeginTime;
                this.submitForm.assessEndTime = this.fatherData.assessEndTime;
                this.submitForm.completeBeginTime = this.fatherData.completeBeginTime;
                this.submitForm.completeEndTime = this.fatherData.completeEndTime;
                // if (this.dialogTitle == "编辑") {
                delete this.submitForm.participantList;
                this.submitForm.participantId = this.dataForm.id;
                this.submitForm.assessId = this.dataForm.assessId;

                //原数据和新添加的数据对比，返回非重复值
                const res= this.dataList.filter((e)=>!this.oldDataList.some((e2)=>parseInt(e2.normId)===parseInt(e.normId)))
                let normIds = res.map(it=>{
                    return parseInt(it.normId) ;
                })
                if (normIds.length == 0) { //不做验证
                  editExamin(this.submitForm)
                      .then(r => {
                          if (r.data.code == 0) {
                              this.saveBtnVisible = false ;
                              this.$message.success("编辑成功");
                              this.$emit("closeDialog");
                              this.$emit("refesData");
                          }

                      })
                      .catch(err => {
                          this.saveBtnVisible = false ;
                          this.$message.error(r.data.msg);
                          this.$emit("closeDialog");
                          this.$emit("refesData");
                      });
                }else{
                    checkitem(this.fatherData.id, normIds.toString()) //验证新增的指标是否有重复
                        .then(r => {
                            if (!r.data.msg) {
                                editExamin(this.submitForm)
                                    .then(r => {
                                        if (r.data.code == 0) {
                                            this.saveBtnVisible = false ;
                                            this.$message.success("编辑成功");
                                            this.$emit("closeDialog");
                                            this.$emit("refesData");
                                        }
                                    })
                                    .catch(err => {
                                        this.saveBtnVisible = false ;
                                        this.$message.error(r.data.msg);
                                        this.$emit("closeDialog");
                                        this.$emit("refesData");
                                    });
                            }else{
                                this.saveBtnVisible = false ;
                                this.$message.error(r.data.msg) ;
                            }
                        });
                }
            } else {
                console.log("error submit!!");
                return false;
            }
        });
    },
    // 初始化
    init(data,editData) {
        this.visible = true;
        this.fatherData = data.data;
        //this.getTemplateName();//模板
        if (editData) {
            if (editData) {
                this.dialogTitle = "修改指标";
                this.dataForm = editData;
                this.getNormByUserId(editData.id) ;
                this.getNormDataTypes() ; //数据获取方式列表
            }
        }
    },
    // 关闭
    closeDialog() {
      this.visible = false;
      this.$emit("closeDialog");
    },
    //获取个人的所有指标列表
    getNormByUserId(id){
        this.loading = true ;
        getNormByTypeAndUserId(id).then(r => {
            if (r.data.code == 0) {
                this.loading = false ;
                this.dataList = r.data.data.map((it, index) => {
                    it.renderIndex = index + 1;
                    return it;
                });
                for (let i = 0 ; i < this.dataList.length ; i++){
                    this.dataList[i].name = this.dataList[i].normName ;
                    this.dataList[i].type = this.dataList[i].normType ;
                }
                //将目标值单独放到数组中，为以后验证做准备
                this.targetDataForm.itemSetForm =  this.dataList.map(it=>{
                    return {'targetValue':it.targetValue,'normId':parseInt(it.normId)}
                })

                this.oldDataList = this.dataList ; //保留一份原始数据
            }
        }) .catch(err => {
            this.$message.error(r.data.msg);
        });
    } ,
    //数据获取方式列表
    getNormDataTypes(){
        remoteDict("sys_norm_sjhqfs").then(response => {
            this.dataFromList = response.data.data;
        });
    },
  }
};
</script>

<style lang="scss">
.tabBox {
  width: 100%;
  .btnBox {
    display: flex;
    justify-content: space-between;
  }
}
</style>
